package com.own.component.elastic.util;

import com.alibaba.fastjson2.JSON;
import com.own.component.elastic.core.base.hook.BaseElasticFieldHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ElasticFieldHandlerRegisterUtil
 *
 * @author chenxueli
 * @date 2024-03-11 15:48:03
 */
@Slf4j
@Component
public class ElasticFieldHandlerRegisterUtil {

    /**
     * 存放处理key和对应处理器的map
     */
    static final Map<String, BaseElasticFieldHandler<? extends Annotation>> HANDLER_KEY_MAP = new HashMap<>();
    /**
     * 存放高级注解和对应处理器的map
     */
    static final Map<Class<? extends Annotation>, BaseElasticFieldHandler<? extends Annotation>> HANDLER_TYPE_MAP = new HashMap<>();
    /**
     * 存放处理key和对应支持的处理类型的map
     */
    static final Map<String, Set<Class<?>>> HANDLER_KEY_TYPE_MAP = new HashMap<>();
    /**
     * 存放高级注解和对应支持的处理类型的map
     */
    static final Map<Class<? extends Annotation>, Set<Class<?>>> HANDLER_TYPE_TYPE_MAP = new HashMap<>();
    /**
     * 存放处理的类型和对应的处理key的map
     */
    static final Map<Class<?>, String> HANDLER_TYPE_KEY_MAP = new HashMap<>();

    @Resource
    private List<BaseElasticFieldHandler<? extends Annotation>> handlerList;

    @PostConstruct
    private void init() {
        var textList = new ArrayList<String>();
        for (var handler : handlerList) {
            var key = handler.key();
            if (StringUtils.isBlank(key)) {
                continue;
            }
            var clazzList = handler.clazzList();
            if (clazzList.isEmpty()) {
                continue;
            }
            var types = new HashSet<>(handler.clazzList());
            HANDLER_KEY_MAP.put(key, handler);
            HANDLER_KEY_TYPE_MAP.put(key, types);
            var annotation = handler.annotation();
            // 注册类型处理器
            if (annotation != null) {
                HANDLER_TYPE_MAP.put(annotation, handler);
                HANDLER_TYPE_TYPE_MAP.put(annotation, types);
            }
            // 类型key信息注册
            if (types.size() == 1) {
                HANDLER_TYPE_KEY_MAP.put(handler.clazzList().getFirst(), key);
            }
            textList.add(key);
        }
        log.info("成功加载ElasticSearch类型mapping【{}】", JSON.toJSONString(textList));
    }

}
